/* eslint-disable jsx-a11y/anchor-is-valid */
import { Button, Form, Input, SpinLoading, Toast, Image } from "antd-mobile";
import Bg from "../../image/bg1.jpg";
import Icons from "../../image/Icon.png";
import styles from "./index.module.css";
import { useEffect, useState } from "react";
import request from "../../axios";

const Login = () => {
  const [iconVis, setIconVis] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [isSending, setIsSending] = useState(false);
  const [form] = Form.useForm();

  // 发送验证码处理函数
  const handleSendCode = async () => {
    // 如果正在倒计时或发送中，不执行任何操作
    if (countdown > 0 || isSending) {
      Toast.show({
        content: "请勿重复发送验证码",
      });
      return
    }

    // 获取手机号码（这里需要从表单中获取，示例中简化处理）
    const phoneNumber = form.getFieldValue("phone");

    // 简单验证手机号码格式
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      Toast.show({
        content: "手机号格式错误",
      });
      return;
    }

    setIsSending(true);
    try {
      // API调用
      await request.get("/user/send_sms_code", {
        phone: phoneNumber,
      });

      Toast.show({
        content: "验证码发送成功",
      });

      // 启动倒计时
      setCountdown(60);

      // 创建倒计时定时器
      const timer = setInterval(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);

      // 倒计时结束后清理
      setTimeout(() => {
        clearInterval(timer);
        setIsSending(false);
      }, 60000);
    } catch (error: any) {
      Toast.show({
        content: "验证码发送失败",
      });
      console.error("验证码发送失败:", error);
      setIsSending(false);
    }
  };

  const handleSubmit = async () => {
    const phoneNumber = form.getFieldValue("phone");
    const codeNumber = form.getFieldValue("code");
    if (!phoneNumber) {
      Toast.show("请输入手机号");
      return;
    }
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      Toast.show({
        content: "手机号格式错误",
      });
      return;
    }
    if (!codeNumber) {
      Toast.show("请输入验证码");
      return;
    }

    try {
      const { code, data } = await request.post("/user/sms_login", {
        phone: phoneNumber,
        code: codeNumber,
      });
      if (code === 200) {
        Toast.show({
          content: "登录成功",
        });
        localStorage.setItem("info", JSON.stringify(data));
        localStorage.setItem("token", data?.token);
        setIconVis(true);
        setTimeout(() => {
          window.location.href = "/page";
        }, 1000);
      } else {
        Toast.show({
          content: "登录失败",
        });
      }
    } catch (error: any) {}
  };

  useEffect(() => {
    if (localStorage.getItem("token")) {
      window.location.href = "/page";
    }
  }, []);

  return (
    <div className={styles.tab} style={{ backgroundImage: `url(${Bg})` }}>
      <div
        className={styles.masks}
        style={{ display: iconVis ? "flex" : "none" }}
      >
        <Image
          src={Icons}
          className={styles.logo}
          style={{ width: "80px", height: "114px" }}
        />
        <SpinLoading
          color="white"
          style={{ "--size": "48px", display: iconVis ? "block" : "none" }}
        />
      </div>
      <div
        className={styles.mask}
        style={{ display: iconVis ? "none" : "flex" }}
      >
        <div className={styles.phone}>手机验证码登录</div>
        <div className={styles.zhegai}></div>
        <Form
          layout="horizontal"
          form={form}
          footer={
            <Button
              className={styles.button}
              block
              type="submit"
              color="primary"
              size="large"
              onClick={handleSubmit}
            >
              提交
            </Button>
          }
          style={{ width: "85%" }}
        >
          <Form.Item name="phone" label="+86" className={styles.input_title}>
            <Input type="number" placeholder="请输入手机号码" />
          </Form.Item>
          <Form.Item
            label="验证码"
            name="code"
            extra={
              <a
                onClick={handleSendCode}
                style={{
                  color: countdown > 0 ? "#999" : "#1677ff",
                  cursor: countdown > 0 ? "not-allowed" : "pointer",
                  marginLeft: 8,
                }}
              >
                {countdown > 0 ? `${countdown}s` : "发送验证码"}
              </a>
            }
          >
            <Input type="number" placeholder="请输入验证码" />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
